package com.platform.auth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.auth.model.PermissionDO;
import com.platform.auth.dto.PermissionAddDTO;
import com.platform.auth.dto.PermissionUpdateDTO;
import com.platform.auth.model.vo.PermissionVO;
import com.platform.auth.service.AuthService;
import com.platform.common.annotation.ApiResponseBody;
import com.platform.common.entity.PageResult;
import com.platform.common.result.ApiException;
import com.platform.common.result.ApiExceptionEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author shuc
 */
@ApiResponseBody
@Controller
@RequestMapping("/manage/permission")
public class ManageController {
    @Resource
    private AuthService authService;

    @GetMapping("/page")
    public PageResult<PermissionVO> page(@RequestParam Integer page,
                                         @RequestParam Integer size) {
        Page<PermissionDO> permissionDOPage = authService.page(page, size);
        return PageResult.<PermissionVO>builder()
                .total(permissionDOPage.getTotal())
                .rows(PermissionDO.toPermissionVOList(permissionDOPage))
                .build();
    }

    @PutMapping("/update")
    public Boolean update(@RequestBody PermissionUpdateDTO permissionUpdateDTO) {
        Boolean result = authService.updateById(PermissionDO.from(permissionUpdateDTO));
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }

    @PostMapping("/add")
    public Boolean add(@RequestBody PermissionAddDTO permissionAddDTO) {
        PermissionDO permissionDO = PermissionDO.from(permissionAddDTO);
        Boolean result = authService.save(permissionDO);
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }

    @DeleteMapping("/delete")
    public Boolean delete(@RequestParam String id) {
        Boolean result = authService.removeById(id);
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }
}
